<template>
  <div class="createPost-container">
    <el-form class="form-container" :model="postForm" :rules="rules" ref="postForm">

      <sticky :className="'sub-navbar '+postForm.status">
        <el-button style="margin-left: 10px;" type="info" @click="handleviewShowClick">预览
        </el-button>
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm()">发布
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <div class="postInfo-container">
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="110px" label="栏目资讯：" class="postInfo-container-item" prop="brand">
                    <el-cascader change-on-select placeholder="请选择" expand-trigger="click" :options="sections"
                      v-model="sectionIds"></el-cascader>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-tooltip class="item" effect="dark" content="请输入标题" placement="top">
                  <el-form-item label-width="110px" label="标题：" class="postInfo-container-item" prop="title">
                    <el-input style="min-width:950px" placeholder="请输入标题" maxlength="100" v-model="postForm.title">
                      <template slot="append">您还可以输入{{ words - postForm.title.length }}个字</template>
                    </el-input>
                  </el-form-item>
                </el-tooltip>
              </el-row>
              <el-row>
                <el-form-item label="是否为AD（广告）：">
                  <el-radio-group v-model="postForm.isAd">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item label="是否为热点推荐：">
                  <el-radio-group v-model="postForm.recommend">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-row>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="110px" label="投放平台：" class="postInfo-container-item" prop="nickname">
              <multiselect style="line-height:initial" v-model="publishPlatform" :options="plat"
                placeholder="选择平台" selectLabel="选择" :multiple="true" deselectLabel="删除" track-by="value" label="label">
              </multiselect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <span>注：如果选择了"全平台",则只显示全平台</span>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上传封面：">
              <el-upload style="margin-left:10px" :headers="headers" action="/tools/oss/upload"
                :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleUploadSuccess"
                accept=".png,.jpg,.jpeg,.gif" list-type="picture" :file-list="fileList" :limit="2">
                <el-button size="small" type="primary">上传封面</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="110px" label="设置标签：" class="postInfo-container-item" prop="nickname">
              <multiselect style="line-height:initial" v-model="postForm.labelsVal" :options="labels"
                @search-change="getLabelOptions" placeholder="搜索标签" selectLabel="选择" :multiple="true" deselectLabel="删除"
                track-by="id" :internalSearch="false" label="name">
                <span slot='noResult'>无搜索结果</span>
              </multiselect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="110px" label="投放区域：" class="postInfo-container-item" prop="nickname">
              <multiselect style="line-height:initial" v-model="postForm.areaVal" :options="areaOptions"
                placeholder="选择区域" selectLabel="选择" :multiple="true" deselectLabel="删除" track-by="value" label="label">
              </multiselect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <span>注：如果选择了"全国",则不能选择其他省份</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <div class="editor-container">
              <el-tooltip class="item" effect="dark" content="请输入内容" placement="top">
                <el-form-item label-width="110px" label="内容：" class="postInfo-container-item" prop="content">
                  <Tinymce :height=400 ref="editor" v-model="postForm.content" :value="postForm.content" />
                </el-form-item>
              </el-tooltip>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label-width="110px" label="设置权重：" class="postInfo-container-item" prop="nickname">
              <el-input-number v-model="postForm.weight" :step="1"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label-width="110px" label="设置浏览量：" class="postInfo-container-item" prop="nickname">
              <el-input-number v-model="postForm.view" :step="1"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label-width="110px" label="设置点赞数：" class="postInfo-container-item" prop="number">
              <el-input-number v-model="postForm.likeCount" :step="1"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <div class="viewShow">
        <el-dialog :show-close="false" :visible.sync="showDialog">
          <div class="information-cont">
            <h3>{{ postForm.title }}</h3>
            <div class="smallLine">
              <span class="time">{{ nowDate|dateformat('YYYY-MM-DD HH:mm') }}</span>
            </div>
            <div class="artical-cont" v-html="postForm.content"></div>
          </div>
        </el-dialog>
      </div>
    </el-form>
  </div>
</template>

<script>
  import Tinymce from '@/components/Tinymce';
  import Upload from '@/components/Upload/headImage';
  import MDinput from '@/components/MDinput';
  import Sticky from '@/components/Sticky'; // 粘性header组件
  import Multiselect from 'vue-multiselect'; // 使用的一个多选框组件，element-ui的select不能满足所有需求
  import 'vue-multiselect/dist/vue-multiselect.min.css'; // 多选框组件css
  import { validateURL } from '@/utils/validate';
  import { add, getSectionCascade, getInfoLabels } from '@/api/advisory';
  import { getAreaList } from '@/api/activity';
  import { getToken } from '@/utils/auth' // 验权

  export default {
    name: 'add',
    components: { Tinymce, MDinput, Upload, Sticky, Multiselect },
    data() {
      const validateRequire = (rule, value, callback) => {
        if (value === '') {
          this.$message({
            message: this.i18n[rule.field] + '为必填项',
            type: 'error',
            duration: 1000
          });
          callback(new Error(this.i18n[rule.field] + '为必填项'));
        } else {
          callback();
        }
      };
      const validateArrRequire = (rule, value, callback) => {
        if (value.length === 0) {
          this.$message({
            message: this.i18n[rule.field] + '为必填项',
            type: 'error'
          });
          callback(new Error(this.i18n[rule.field] + '为必填项'));
        } else {
          callback();
        }
      };
      const validateSourceUri = (rule, value, callback) => {
        if (value) {
          if (validateURL(value)) {
            callback();
          } else {
            this.$message({
              message: 'url填写不正确',
              type: 'error'
            });
            callback(new Error(this.i18n[rule.field] + '为必填项'));
          }
        } else {
          this.$message({
            message: this.i18n[rule.field] + '为必填项',
            type: 'error'
          })
          callback(new Error(this.i18n[rule.field] + '为必填项'))
        }
      };
      return {
        labels: [],
        areaOptions: [], // 省份列表
        sections: [],
        sectionIds: [],
        headers: {},
        fileList: [],
        publishPlatform: [],

        tagValue: '',
        words: 100,
        plat: [
          {
            value: 1,
            label: "全平台"
          },
          {
            value: 2,
            label: "教师端小程序"
          },
          {
            value: 3,
            label: "学生家长端"
          }
        ],
        postForm: {
          sId: '',
          title: '',
          content: '',
          cover: '',
          isAd: 0,
          recommend: 0,
          labelsVal: [],
          areaVal: [],
          provinceIds: [],
          likeCount: 10,
          view: 10,
          weight: 100,
        },
        loading: false,
        i18n: {
          title: '标题'
        },
        rules: {
          title: [{ validator: validateRequire }]
        },

        showDialog: false,
        nowDate: '', // 当前时间
      };
    },
    mounted() {
      this.headers = { accessToken: getToken() }
      this.getSectionCascade()
      this.getLabelOptions('')
      this.fetchAreaData()
    },
    watch: {
      // 监控是否选择了“全国” 如果选择了，那么不能选择其他省份
      'postForm.areaVal'(e) {

        if (e.label || e.toString() == []) {
          return
        } else if (e[e.length - 1].value === 6666) {
          this.postForm.areaVal = {
            value: 6666,
            label: '全国',
            children: [],
          }
          return
        }
        let flag = false;
        e.forEach(item => {
          if (item.value === 6666) {
            flag = true;
          }
        })
        if (flag) {
          this.postForm.areaVal = {
            value: 6666,
            label: '全国',
            children: [],
          }
        }
      },

      // 监控是否选择了“全平台” 如果选择了，那么不能选择其他平台
      // 'postForm.publishPlatform'(e) {

      //   const arr = []
      //   for (let i in e) {
      //     let o = {};
      //     o[i] = arr[i];
      //     arr.push(o)
      //   }
      //   if (e.label || e.toString() == []) {
      //     return
      //   } else {
      //     arr.forEach((item, index) => {
      //       if (item.value === 1) {
      //         this.postForm.publishPlatform = e[index]
      //         return
      //       }
      //     })
      //   }
      //   let flag = false;
      //   arr.forEach(item => {
      //     if (item.value === 1) {
      //       flag = true;
      //     }
      //   })
      //   if (flag) {
      //     this.postForm.publishPlatform = {
      //       value: 1,
      //       label: '全平台',
      //     }
      //   }
      // },
    },
    methods: {
      // 查看预览
      handleviewShowClick() {
        this.nowDate = new Date().getTime();
        this.showDialog = true;
      },
      // 投放区域
      fetchAreaData() {
        getAreaList().then(response => {
          this.areaOptions = response.data;
          this.areaOptions.unshift({
            value: 6666,
            label: '全国',
            children: [],
          })
        })
      },
      getLabelOptions(title) {
        getInfoLabels({ labelName: title }).then(response => {
          const { code, data } = response
          if (code == 0) {
            this.labels = data;
          }
        })
      },
      getSectionCascade() {
        getSectionCascade().then(response => {
          const { code, data } = response
          if (code == 0) {
            this.sections = data;
            this.sectionIds = [data[0]['value']]
          }
        })
      },
      handleUploadSuccess(rst, file, fileList) {
        let { code, data: { picUrlList } } = rst;
        let { postForm } = this;
        if (code == 0) {
          postForm['cover'] = picUrlList[0];
          this.postForm = postForm;
          this.fileList = [{ name: file.url, url: file.url }];
        }
      },
      handlePreview(file) {
      },
      handleRemove(file, fileList) {
        this.postForm['cover'] = '';
      },
      handleClose(tag) {
        this.postForm.labels.splice(this.postForm.labels.indexOf(tag), 1);
      },
      handleFilter() {
        const { tagValue, postForm: { labels } } = this;
        if (tagValue.trim().length == 0) { return }
        if (labels.some(e => e == tagValue)) {
          this.$message({
            message: '不能添加相同的标签',
            type: 'error'
          });
          return;
        }

        this.postForm.labels.push(tagValue);
        this.tagValue = '';
      },
      submitForm() {
        console.log(this.postForm.publishPlatform)
        this.$refs.postForm.validate(valid => {
          if (valid) {
            // this.loading = true;
            let params = this.postForm;
            const { content, cover, labelsVal, areaVal, provinceIds, } = params;
            const { sectionIds } = this;

            if (content.trim().length == 0 || content == '<p><br data-mce-bogus="1"></p>' || content == '<p>&nbsp;</p>' || content == '<p><br></p>') {
              this.$message({
                message: '内容不能为空',
                type: 'error',
                duration: 1000
              });
              this.loading = false;
              return;
            }
          
            if (cover.length == 0) {
              this.$message({
                message: '请上传封面',
                type: 'error',
                duration: 1000
              });
              this.loading = false;
              return;
            }
            if (sectionIds.length > 0) {
              params['sId'] = sectionIds[sectionIds.length - 1]
            }
            if (labelsVal.length > 0) {
              let labels = []
              labelsVal.map(e => labels.push(e.id))
              params['labels'] = labels
            }
            var str = ''
            if (this.publishPlatform) {
              let labels = []
              this.publishPlatform.map((item) => {
                labels.push(item.value)
              })
              for(var i =0;i<labels.length;i++){
                if(labels[i] == 1 &&labels.length>1){
                  params['publishPlatform'] = '1'
                  break
                }else if(labels[i] != 1 &&labels.length>1){
                  str += labels[i].toString()
                  params['publishPlatform'] = str.split('').join(',')
                }else{
                  params['publishPlatform'] =  labels[i] + ''
                }
              }
            }
           
            if (areaVal.length === 0) {
              params['provinceIds'] = [6666]
            } else {
              if (areaVal.value == 6666) {
                params['provinceIds'] = [6666]
              } else {
                params['provinceIds'] = []
                areaVal.forEach(item => {
                  params['provinceIds'].push(item.value)
                });
              }
            }
            if(this.publishPlatform.length == 0){
              this.$message({
                message: '投放平台不能为空',
                type: 'error',
                duration: 1000
              });
            }else{
              add(params).then(response => {
              const { code } = response
              this.postForm.labelsVal = labelsVal
              if (code == 0) {
                this.$notify({
                  title: '成功',
                  message: '资讯发布成功',
                  type: 'success',
                  duration: 1000
                });
                // this.loading = false;
                this.$router.push({ path: '/advisory/table' })
              } else {
                this.$message({
                  title: '失败',
                  message: message,
                  type: 'error',
                  duration: 2000
                })
              }
            }).catch(err => { })
            }
          
          } else {
            return false;
          }
        });
      }
    }
  };
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  @import 'src/styles/mixin.scss';

  .viewShow {

    /deep/ .el-dialog {
      width: 350px;
      height: 760px;
      padding: 100px 12px;
      border-radius: 50px;
      background: url('../../assets/phone.png') no-repeat;
      background-size: 100% 100%;

      .el-dialog__header {
        padding: 0;
      }

      .el-dialog__body {
        padding: 0;
        background: #fff;
        width: 100%;
        height: 100%;

        .information-cont {
          padding: 0 15px;
          background: #fff;
          white-space: normal;
          word-break: break-all;
          height: 100%;
          overflow-y: auto;

          h3 {
            font-size: 20px;
            line-height: 32px;
            color: #333333;
            font-weight: bold;
            padding-top: 15px;
            margin: 0;

          }

          .smallLine {
            display: flex;
            display: -webkit-flex;
            justify-content: space-between;
            -webkit-justify-content: space-between;
            align-items: center;
            -webkit-align-items: center;
            font-size: 13px;
            color: #BBB;
            padding-top: 20px;
            padding-bottom: 17px;
            border-bottom: 1px solid #E5E8ED;
          }

          .artical-cont {
            padding-top: 16px;
            font-size: 15px;
            overflow: hidden;

            img {
              width: 100%;
            }
          }

        }

      }

    }

  }

  .upload-img-dev {
    width: 320px;
    height: 160px;
    position: absolute;
    right: 200px;
    bottom: 60px;
    z-index: 3;
  }

  .upload-img {
    width: 320px;
    height: 160px;
  }

  .tagLeft {
    margin-left: 10px;
  }

  .title-prompt {
    position: absolute;
    right: 0px;
    font-size: 12px;
    top: 10px;
    color: #ff4949;
  }

  .createPost-container {
    position: relative;

    .createPost-main-container {
      padding: 40px 45px 20px 300px;

      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;

        .postInfo-container-item {
          float: left;
        }
      }

      .editor-container {
        min-height: 500px;

        .editor-upload-btn-container {
          text-align: right;
          margin-right: 10px;

          .editor-upload-btn {
            display: inline-block;
          }
        }
      }
    }

    .word-counter {
      width: 40px;
      position: absolute;
      right: -10px;
      top: 0px;
    }
  }
</style>